<?php
declare (strict_types = 1);

namespace app\api\controller\User;

use app\BaseController;
use app\common\model\Config as ConfigModel;
use app\common\model\Region as RegionModel;
use app\common\model\User\User as UserModel;
use app\common\validate\User\User as UserValidate;
use Exception;
use think\exception\ValidateException;

class Auth extends BaseController
{
    public function login() {
        // 接收参数 => code 授权凭证
        $code = $this->request->param('code');

        if(empty($code)) {
            $this->error('授权失败');
        }

        // 调用微信Api通过授权凭证换取openid
        $openid = $this->code2Session($code);

        if(empty($openid)) {
            $this->error('获取临时登录凭证失败');
        }

        $User = UserModel::where(['openid' => $openid])->find();

        if(!$User) {
            $this->error('请先绑定账号','1');
        }

        // 返回微信用户数据
        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'region_text' => $User['region_text']
        ];

        $this->success('授权成功',null,$data);

    }

    public function bind() {
        $params = $this->request->param();

        if(empty($params['code'])) {
            $this->error('授权失败');
        }

        // 调用微信Api通过授权凭证换取openid
        $openid = $this->code2Session($params['code']);

        if(empty($openid)) {
            $this->error('获取临时登录凭证失败');
        }

        $User = UserModel::where(['email' => $params['email']])->find();

        if($User) {
            $password = md5($params['password'].$User['salt']);

            if($password != $User['password']) {
                $this->error('密码错误');
            }

            $User->openid = $openid;

            $result = $User->save();

            if($result !== FALSE) {  
                $this->success('绑定成功');
            }else {
                $this->error('绑定失败');
            }

        }else {
            try {
                // 生成密码盐
                $salt = build_ranstr();

                // 加密
                $password = md5($params['password'].$salt);

                // 查询注册积分
                $RegisterPoint = ConfigModel::where(['key' => 'RegisterPoint'])->value('value');

                $data = [
                    'email' => $params['email'],
                    'password' => $password,
                    'salt' => $salt,
                    'point' => $RegisterPoint,
                    'sex' => 0,
                    'auth' => 0,
                    'vip' => 1,
                    'openid' => $openid
                ];

                validate(UserValidate::class)->scene('weixin')->check($data);

                $result = UserModel::create($data);

                if($result === FALSE)
                {
                    throw new Exception('绑定失败');
                }

            } catch (ValidateException $e) {
                $this->error($e->getError());
            } catch (Exception $error) {
                $this->error($error->getMessage());
            }

            $this->success('绑定成功');
        }
    }

    public function profile() {
        $params = $this->request->param();

        $User = UserModel::find($params['id']);

        if(!$User) {
            $this->error('用户不存在');
        }

        $data = [
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content'],
        ];

        // halt($params['code']);

        if(!empty($params['code'])) {
            $parentpath = RegionModel::where(['code' => $params['code']])->value('parentpath');

            if(!$parentpath) {
                $this->error('所选地区不存在');
            }

            [$province,$city,$district] = explode(',',$parentpath);

            $data['province'] = $province;
            $data['city'] = $city;
            $data['district'] = $district;
        }

        if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {

            $cover = upload('cover');

            if($cover['code'] === 0)
            {
                $this->error($cover['msg']);
            }

            $data['cover'] = $cover['data'];
        }

        $result = UserModel::update($data,['id' => $User['id']]);

        
        if($result !== FALSE) {
            if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
            {
                @is_file($User['cover']) && @unlink($User['cover']);
            }

            $user = UserModel::find($User['id']);

            // 返回微信用户数据
            $data = [

                'id' => $user['id'],
                'email' => $user['email'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar_cdn'],
                'cover' => $user['cover_cdn'],
                'sex' => $user['sex'],
                'sex_text' => $user['sex_text'],
                'province' => $user['province'],
                'city' => $user['city'],
                'district' => $user['district'],
                'createtime' => $user['createtime'],
                'content' => $user['content'],
                'point' => $user['point'],
                'vip' => $user['vip'],
                'auth' => $user['auth'],
                'region_text' => $user['region_text'],
                'region' => $user['region']
            ];

            $this->success('更新成功',null,$data);
        }else {
            if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
            {
                @is_file($data['cover']) && @unlink($data['cover']);
            }
        }
    }


    protected function code2Session($code) {
        $appid = ConfigModel::where(['key' => 'Appid'])->value('value');

        // 密钥
        $AppSecret = ConfigModel::where(['key' => 'AppSecret'])->value('value');

        $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret=$AppSecret&js_code={$code}&grant_type=authorization_code";

        $result = $this->https_request($ApiUrl);

        $data = json_decode($result,true);

        if(!empty($data['openid'])) {
            return $data['openid'];
        }else {
            return FALSE;
        }
    }

    protected function https_request($url,$data = null)
    {
        if(function_exists('curl_init')){
        $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }
}
